package com.kevin.spring.service;

import com.kevin.core.RpcRequest;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ConcurrentHashMap;

public class HandlerMapping {

    private static volatile HandlerMapping instance;

    public static ConcurrentHashMap<String,BeanMethod> handlerMethodMap = new ConcurrentHashMap<>();

    private HandlerMapping() {
    }

    public static HandlerMapping getInstance(){
        if(null==instance){
            synchronized (HandlerMapping.class){
                if(null==instance){
                    instance = new HandlerMapping();
                }
            }
        }
        return instance;
    }


    public Object invoke(RpcRequest rpcRequest){
        BeanMethod beanMethod = handlerMethodMap.get(rpcRequest.getClassName()+"."+rpcRequest.getMethodName());
        if(null!=beanMethod){
            try {
                return beanMethod.getMethod().invoke(beanMethod.getBean(),rpcRequest.getParams());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
